let config = {
  qiniuUploadURL: '',
  qiniuImageURLPrefix: '',
  qiniuUploadToken: '',
  qiniuUploadTokenURL: '',
  qiniuUploadTokenFunction: null
}

function QiniuResponse(isSuccess, responseData){
  this.success = isSuccess;
  this.data = responseData;
}

function Qiniu(filePath) { this.filePath = filePath; };

Qiniu.init = (options)=>{
  options.uploadURL ? (config.qiniuUploadURL = options.uploadURL) : console.error('qiniu uploader need uploadURL');
  config.qiniuImageURLPrefix = (options.domain) || config.qiniuImageURLPrefix;
  if(options.uptoken) {
    config.qiniuUploadToken = options.uptoken;
  } else if(options.uptokenURL) {
    config.qiniuUploadTokenURL = options.uptokenURL;
  } else if(options.uptokenFunc) {
    config.qiniuUploadTokenFunction = options.uptokenFunc;
  }
}


function upload(complete) {
  let filePath = this.filePath, url = config.qiniuUploadURL;

  if (config.qiniuUploadToken) {
    doUpload(filePath, success, fail, options);
  } else if (config.qiniuUploadTokenURL) {
    getQiniuToken(function () {
      doUpload(filePath, success, fail, options);
    });
  } else if (config.qiniuUploadTokenFunction) {
    config.qiniuUploadToken = config.qiniuUploadTokenFunction();
  } else {
    console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
    return;
  }
}
Qiniu.prototype.upload = upload;

function doUpload(filePath, success, fail, options) {
  var url = config.qiniuUploadURL;
  var fileName = filePath.split('//')[1];

  let token = config.qiniuUploadToken;
  


  if (options && options.key) {
    fileName = options.key;
  }
  var formData = {
    'token': config.qiniuUploadToken,
    'key': fileName
  };
  wx.uploadFile({
    url: url,
    filePath: filePath,
    name: 'file',
    formData: formData,
    success: function (res) {
      var dataString = res.data
      var dataObject = JSON.parse(dataString);
      //do something
      var imageUrl = config.qiniuImageURLPrefix + dataObject.key;
      dataObject.imageURL = imageUrl;
      console.log(dataObject);
      success(dataObject);
    },
    fail: function (error) {
      console.log(error);
      fail(error);
    }
  })
}
Qiniu.prototype.doUpload = doUpload;
